<?php


namespace App\Http\Controllers\User;


use App\Http\Common\BaseController;
use App\Http\Validator\StudyScheduleValidator;
use App\Models\StudySchedule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\File\Exception\UploadException;


class StudyScheduleController extends BaseController
{
    /**
     * 添加学习进度
     * @param Request $request
     * @param StudyScheduleValidator $validator
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function addSchedule(Request $request, StudyScheduleValidator $validator){
        $params = $request->only(['date', 'content']);
        $imgFile = $request->file('img');

        //判断输入格式
        if (!$validator->setScene('add')->check($params)){
            return $this->returnJson(BaseController::FIELD_ERROR, $validator->getError());
        }

        if ($imgFile == null){
            return $this->returnJson(BaseController::FIELD_ERROR, '文件没有上传');
        }

        //获取文件后缀
        $suffix = $imgFile->getClientOriginalExtension();

        //判断文件后缀
        $rule = ['jpg', 'png', 'gif','jpeg'];
        if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

        //判断文件大小
        $fileSize = $imgFile->getSize();
        if ($fileSize > 10 * 1024 * 1024){
            return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
        }
        $fileUrl = md5(time() . $imgFile->getClientOriginalName()) . '.' . $suffix;

        //获取用户id
        $user_id = $request->userId;

        DB::beginTransaction();
        try {
            //插入文件
            if (!$file = $this->uploadOss('wdad/studySchedule', $fileUrl, $imgFile->getRealPath())){
                throw new UploadException();
            }

            //插入数据
            StudySchedule::insert([
                'user_id'       =>  $user_id,
                'date'          =>  $params['date'],
                'content'       =>  $params['content'],
                'img'           =>  $file['oss-request-url'],
                'create_time'   =>  time()
            ]);

            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->returnJson(BaseController::ERROR, '添加学习进度失败');
        }

        return $this->returnJson(BaseController::SUCCESS, '添加学习进度成功');
    }

    /**
     * 获取学习进度
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getSchedule(Request $request){
        $data = StudySchedule::where('user_id', $request->userId)
            ->orderBy('create_time')
            ->select(['content', 'img'])
            ->get();

        return $this->returnJson(BaseController::SUCCESS, '数据获取成功', $data);
    }
}
